from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_required
from decimal import Decimal

from app import db
from app.models.supermarket import Supermarket
from app.models.blind_box import BlindBox
from app.models.order import Order
from app.models.supermarket_application import SupermarketApplication

supermarket = Blueprint('supermarket', __name__, url_prefix='/supermarket')

@supermarket.route('/list')
@login_required
def list():
    """超市列表"""
    # 获取筛选参数
    name = request.args.get('name')
    status = request.args.get('status')
    address = request.args.get('address')
    
    query = Supermarket.query
    
    # 应用筛选条件
    if name:
        query = query.filter(Supermarket.name.like(f'%{name}%'))
    if status:
        query = query.filter(Supermarket.status == int(status))
    if address:
        query = query.filter(Supermarket.address.like(f'%{address}%'))
    
    # 获取所有超市
    supermarkets = query.order_by(Supermarket.rating.desc()).all()
    
    # 获取待审核申请数量
    pending_application_count = SupermarketApplication.query.filter_by(status='pending').count()
    
    return render_template('supermarket/list.html', 
                          supermarkets=supermarkets,
                          pending_application_count=pending_application_count)

@supermarket.route('/detail/<int:market_id>')
@login_required
def detail(market_id):
    """超市详情"""
    market = Supermarket.query.get_or_404(market_id)
    
    # 获取该超市的盲盒
    blind_boxes = BlindBox.query.filter_by(market_id=market_id).all()
    
    # 获取该超市的订单数量
    orders_count = Order.query.filter_by(market_id=market_id).count()
    
    return render_template('supermarket/detail.html', 
                           market=market, 
                           blind_boxes=blind_boxes,
                           orders_count=orders_count)

@supermarket.route('/add', methods=['GET', 'POST'])
@login_required
def add():
    """添加超市"""
    if request.method == 'POST':
        name = request.form.get('name')
        address = request.form.get('address')
        phone = request.form.get('phone')
        business_hours = request.form.get('business_hours')
        description = request.form.get('description')
        status = int(request.form.get('status', 1))
        image_url = request.form.get('image_url')
        
        # 处理经纬度
        longitude = request.form.get('longitude')
        latitude = request.form.get('latitude')
        if longitude and longitude.strip():
            longitude = Decimal(longitude)
        else:
            longitude = None
            
        if latitude and latitude.strip():
            latitude = Decimal(latitude)
        else:
            latitude = None
            
        # 处理评分
        rating = request.form.get('rating')
        if rating and rating.strip():
            rating = Decimal(rating)
        else:
            rating = Decimal('5.0')
        
        # 创建新超市
        new_market = Supermarket(
            name=name,
            address=address,
            phone=phone,
            business_hours=business_hours,
            description=description,
            status=status,
            image_url=image_url,
            longitude=longitude,
            latitude=latitude,
            rating=rating
        )
        
        db.session.add(new_market)
        db.session.commit()
        
        flash('超市添加成功!', 'success')
        return redirect(url_for('supermarket.list'))
        
    return render_template('supermarket/form.html', market=None)

@supermarket.route('/edit/<int:market_id>', methods=['GET', 'POST'])
@login_required
def edit(market_id):
    """编辑超市"""
    market = Supermarket.query.get_or_404(market_id)
    
    if request.method == 'POST':
        market.name = request.form.get('name')
        market.address = request.form.get('address')
        market.phone = request.form.get('phone')
        market.business_hours = request.form.get('business_hours')
        market.description = request.form.get('description')
        market.status = int(request.form.get('status', 1))
        market.image_url = request.form.get('image_url')
        
        # 处理经纬度
        longitude = request.form.get('longitude')
        latitude = request.form.get('latitude')
        if longitude and longitude.strip():
            market.longitude = Decimal(longitude)
        else:
            market.longitude = None
            
        if latitude and latitude.strip():
            market.latitude = Decimal(latitude)
        else:
            market.latitude = None
            
        # 处理评分
        rating = request.form.get('rating')
        if rating and rating.strip():
            market.rating = Decimal(rating)
        else:
            market.rating = Decimal('5.0')
        
        db.session.commit()
        
        flash('超市信息更新成功!', 'success')
        return redirect(url_for('supermarket.detail', market_id=market_id))
        
    return render_template('supermarket/form.html', market=market)

@supermarket.route('/delete/<int:market_id>')
@login_required
def delete(market_id):
    """删除超市"""
    market = Supermarket.query.get_or_404(market_id)
    
    # 检查是否有关联的盲盒
    has_boxes = BlindBox.query.filter_by(market_id=market_id).first() is not None
    
    if has_boxes:
        flash('无法删除该超市，因为存在关联的盲盒商品!', 'danger')
        return redirect(url_for('supermarket.list'))
    
    db.session.delete(market)
    db.session.commit()
    
    flash('超市已删除!', 'success')
    return redirect(url_for('supermarket.list'))

@supermarket.route('/toggle_status/<int:market_id>')
@login_required
def toggle_status(market_id):
    """切换超市状态（营业/休息）"""
    market = Supermarket.query.get_or_404(market_id)
    
    # 切换状态
    market.status = 0 if market.status == 1 else 1
    db.session.commit()
    
    status_text = '营业中' if market.status == 1 else '暂停营业'
    flash(f'超市状态已更改为: {status_text}!', 'success')
    return redirect(url_for('supermarket.list'))

@supermarket.route('/applications')
@login_required
def applications():
    """超市申请列表"""
    # 获取筛选参数
    status = request.args.get('status', '')
    keyword = request.args.get('keyword', '')
    
    query = SupermarketApplication.query
    
    # 应用筛选条件
    if status:
        query = query.filter(SupermarketApplication.status == status)
    
    if keyword:
        query = query.filter(
            (SupermarketApplication.name.like(f'%{keyword}%')) | 
            (SupermarketApplication.address.like(f'%{keyword}%')) |
            (SupermarketApplication.contact_name.like(f'%{keyword}%'))
        )
    
    # 获取所有申请
    applications = query.order_by(SupermarketApplication.apply_time.desc()).all()
    
    # 待审核申请数量(用于徽章显示)
    pending_count = SupermarketApplication.query.filter_by(status='pending').count()
    
    return render_template('supermarket/application_list.html', 
                          applications=applications, 
                          status_filter=status,
                          keyword=keyword,
                          pending_count=pending_count)

@supermarket.route('/applications/<int:app_id>', methods=['GET', 'POST'])
@login_required
def application_detail(app_id):
    """超市申请详情"""
    application = SupermarketApplication.query.get_or_404(app_id)
    
    if request.method == 'POST':
        action = request.form.get('action')
        
        if action == 'approve':
            # 批准申请
            application.status = 'approved'
            db.session.commit()
            
            # 是否创建超市记录
            create_market = request.form.get('create_market') == 'yes'
            if create_market:
                # 创建新超市
                new_market = Supermarket(
                    name=application.name,
                    address=application.address,
                    business_hours=application.business_hours,
                    latitude=application.latitude,
                    longitude=application.longitude,
                    phone=application.contact_phone,  # 临时使用申请人电话
                    description=f"申请人: {application.contact_name}, 电话: {application.contact_phone}\n{application.remark or ''}",
                    status=1  # 默认为营业状态
                )
                
                db.session.add(new_market)
                db.session.commit()
                
                flash(f'已批准申请并创建超市记录: {new_market.name}！', 'success')
                return redirect(url_for('supermarket.detail', market_id=new_market.market_id))
            else:
                flash('已批准申请！', 'success')
                return redirect(url_for('supermarket.applications'))
            
        elif action == 'reject':
            # 拒绝申请
            reject_reason = request.form.get('reject_reason', '')
            if reject_reason:
                # 更新申请状态和备注
                current_remark = application.remark or ''
                application.status = 'rejected'
                application.remark = f"{current_remark}\n\n拒绝理由: {reject_reason}" if current_remark else f"拒绝理由: {reject_reason}"
                db.session.commit()
                
                flash('已拒绝申请！', 'warning')
                return redirect(url_for('supermarket.applications'))
            else:
                flash('请提供拒绝理由！', 'danger')
    
    return render_template('supermarket/application_detail.html', application=application) 